package cn.com.cvit.nc.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.com.cvit.nc.bean.Device;
import cn.com.cvit.nc.bean.Msg;
import cn.com.cvit.nc.bean.Organize;
import cn.com.cvit.nc.bean.Person;
import cn.com.cvit.nc.bean.Subscribe;
import cn.com.cvit.nc.bean.SubscribeSon;
import cn.com.cvit.nc.bean.User;
import cn.com.cvit.nc.service.DeviceService;
import cn.com.cvit.nc.service.OrganizeService;
import cn.com.cvit.nc.service.PersonService;
import cn.com.cvit.nc.service.SubscribeService;
import cn.com.cvit.nc.service.SubscribeSonService;
import cn.com.cvit.nc.service.UserService;
import cn.com.cvit.nc.util.BaseParameter;
import cn.com.cvit.nc.websocket.WebSocketTest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class SubscribeController {

	@Autowired
	SubscribeService subscribeService;
	@Autowired
	UserService userService;
	@Autowired
	SubscribeSonController subscribeSonController;
	@Autowired
	SubscribeSonService subscribeSonService;
	@Autowired
	PersonService personService;
	@Autowired
	OrganizeService organizeService;
	@Autowired
	DeviceService deviceService;
	
	BaseParameter baseParameter =new BaseParameter();

	//看板2018-5-19
	@RequestMapping(value = "/selectSeeBoard", method = RequestMethod.GET)
	@ResponseBody
	public Msg selectSeeBoard(String deviceId,String catagoryId){
		Subscribe subDevice = new Subscribe();
		subDevice.setSubscribeDeviceId(deviceId);
		subDevice.setDeviceClass(catagoryId);
		List<Subscribe> timeDual = subscribeService.selectSeeBoard(subDevice);
		return Msg.success().add("subscribe", timeDual);
	}
	//预约代办连接
	@RequestMapping(value = "/selectWaitURL", method = RequestMethod.GET)
	@ResponseBody
	public Msg selectWaitURL(String email){
		Subscribe sub = new Subscribe();
		sub.setSubscribeUserEmail(email);
		List<Subscribe> list = subscribeService.selectSubscribeStatusByEmailWebService(sub);
		
		SubscribeSon subson = new SubscribeSon();
		subson.setSubscribePartnerId(email);
		List<SubscribeSon> list2 = subscribeSonService.selectSubscribeSonStatusByEmailWebService(subson);
		return Msg.success().add("subscribe", list).add("invited", list2);
	}
	//查询所有预约信息带设备信息1
	@RequestMapping(value = "/getSubscribeAll", method = RequestMethod.GET)
	@ResponseBody
	public Msg getAllSubscribe() {
		List<Subscribe> list = subscribeService.getAllSubscribe();
		if(list.size()>0){
			return Msg.success().add("subscribe", list);
		}else{
			return Msg.fail();
		}
	}

	//根据时间查数据2018-5-16
	@RequestMapping(value = "/selectSubscribeForAll", method = RequestMethod.GET)
	@ResponseBody
	public Msg selectSubscribeForAll(){
		List<Subscribe> list = subscribeService.selectSubscribeForAll();
		Subscribe sub = new Subscribe();
		//字表未来得及处理
		for(int i =0;i<list.size();i++){
			SubscribeSon subSon = new SubscribeSon();
			subSon.setSubscribeId(list.get(i).getId());
			subSon.setSubscribeUserStatus("2");
			subSon.setSubscribeStatus("3");
			subscribeSonService.updateBySubscribeId(subSon);
		}
		//字表接受/拒绝
		for(int i =0;i<list.size();i++){
			SubscribeSon subSon = new SubscribeSon();
			subSon.setSubscribeId(list.get(i).getId());
			subSon.setSubscribeStatus("3");
			subscribeSonService.updateBySubscribeIdTwo(subSon);
		}
		for(int i =0;i<list.size();i++){
			sub.setId(list.get(i).getId());
			sub.setSubscribeStatus("3");
			subscribeService.updateStatusAndFlag(sub);
		}
		if(list.size()>0){
			return Msg.success().add("success", list);
		}else{
			return Msg.fail().add("fail", list);
		}
	}
	//查询所有预约信息带设备信息--flag过滤
	@RequestMapping(value = "/getSubscribeAllByFlag", method = RequestMethod.GET)
	@ResponseBody
	public Msg getSubscribeAllByFlag(@RequestParam(value = "pn", defaultValue = "1") Integer pn,
			@RequestParam(value = "nr", defaultValue = "10") Integer nr) {
		PageHelper.startPage(pn, nr); // 分页查询
		List<Subscribe> list = subscribeService.getSubscribeAllByFlag();//详细信息
		//List<Subscribe> list2 = subscribeService.selectBase();//基础信息
		PageInfo<Subscribe> page = new PageInfo(list, nr);
		return Msg.success().add("pageInfo", page);
	}

	//根据邮箱、姓名、开始时间、结束时间查询预约信息（参数可以为空）flag过滤
	@RequestMapping("/getSubscribeByEmailOrNameOrBTimeOrETime")
	@ResponseBody
	public Msg getSubscribeByEmailOrNameOrBTimeOrETime(
			@RequestParam(value = "subscribe_user_email", defaultValue = "") String email,
			@RequestParam(value = "subscribe_user_name", defaultValue = "") String name,
			@RequestParam(value = "begintime", defaultValue = "") String begintime,
			@RequestParam(value = "endtime", defaultValue = "") String endtime,
			@RequestParam(value = "subscribe_device_id", defaultValue = "") String deviceId
			) {
		List<Subscribe> list = subscribeService.getSubscribeByEmailOrNameOrBTimeOrETime(email, name, begintime,endtime,deviceId);
		if(list.size()>0){
			return Msg.success().add("getSubscribeByEmailOrNameOrBTimeOrETime", list);
		}else{
			return Msg.fail();
		}
	}

	//通过邮箱和姓名判断用户是否存在
	@RequestMapping(value = "/UserByEmail", method = RequestMethod.GET)
	@ResponseBody
	public Msg getUserByEmail(@RequestParam("subscribe_user_email") String email,
			@RequestParam("subscribe_user_name") String name) {
		List<User> list = userService.getEmailAndNameAndTime(email, name);
		for (int i = 0; i < list.size(); i++) {
			return Msg.success().add("successMsg", "用户存在").add("subscribe", list);
		}
		return Msg.fail().add("failMsg", "用户不存在");
	}

	//根据邮箱和姓名查询--后台用--未过滤
	@RequestMapping(value = "/getSubscribeByEmailAndName", method = RequestMethod.GET)
	@ResponseBody
	public Msg getEmailAndName(@RequestParam("subscribe_user_email") String email,
			@RequestParam("subscribe_user_name") String name) {
		/*//this.selectSubscribeForAll();//修改过期数据
		//修改受邀2018-5-17
		List<Subscribe> listSonId = subscribeService.selectSubscribeByEmailForAfterTime(email);
		for(int i=0;i<listSonId.size();i++){
			SubscribeSon son = new SubscribeSon();
			son.setSubscribeId(listSonId.get(i).getId());
			son.setSubscribeStatus("3");//正常结束
			son.setSubscribeUserStatus("2");//拒绝
			subscribeSonService.updateBySubscribeId(son);
		}
		//修改SubscribeStatus（时间过后，把1未通过2通过的，改为‘3.正常结束’）2018-5-17
		subscribeService.updateSubscribeStatus(email, name, "3");*///2018-6-8注释
		List<Subscribe> list = subscribeService.getEmailAndName(email, name);
		return Msg.success().add("getEmailAndName", list);
	}

	//根据邮箱和姓名查询--前台用--已过滤，根据结束时间，过滤掉当前时间之前的预约信息
	@RequestMapping(value = "/getSubscribeByEmailAndNameAndTime", method = RequestMethod.GET)
	@ResponseBody
	public Msg getSubscribeByEmailAndName(@RequestParam("subscribe_user_email") String email,
			@RequestParam("subscribe_user_name") String name) {
		List<Subscribe> list = subscribeService.getEmailAndNameAndTime(email, name);
		return Msg.success().add("getSubscribeByEmailAndName", list);
	}

	//根据设备ID查询
	@RequestMapping(value = "/getSubscribeById", method = RequestMethod.GET)
	@ResponseBody
	public Msg getSubscribeById(@RequestParam("subscribe_device_id") String subscribe_device_id) {
		List<Subscribe> list = subscribeService.getId(subscribe_device_id);
		if(list.size()>0){
			return Msg.success().add("getSubscribeById", list);
		}else{
			return Msg.fail();
		}
	}
	
	//根据类别ID查指定类别下的预约信息
	@RequestMapping(value = "/selectDeviceCatagorySubscribeAll", method = RequestMethod.GET)
	@ResponseBody
	public Msg selectDeviceCatagorySubscribeAll(@RequestParam("deviceCatagoryId")String deviceCatagoryId){
		List<Subscribe> list=subscribeService.selectDeviceCatagorySubscribeAll(deviceCatagoryId);
		if(list.size()>0){
			return Msg.success().add("success", list);
		}else{
			return Msg.fail();
		}
	}

	//根据设备ID查询，，，过滤getSubscribeByIdAndStatus
	@RequestMapping(value = "/getSubscribeByIdAndStatus", method = RequestMethod.GET)
	@ResponseBody
	public Msg getSubscribeByIdAndStatus(@RequestParam("subscribe_device_id") String subscribe_device_id) {
		List<Subscribe> list = subscribeService.getSubscribeByIdAndStatus(subscribe_device_id);
		if(list.size()>0){
			return Msg.success().add("getSubscribeByIdAndStatus", list);
		}else{
			return Msg.fail();
		}
	}

	//根据预约id查询***带设备信息---带受邀人信息
	@RequestMapping(value = "/getSubscribeDetailedWithDeviceDataBySubscribeId", method = RequestMethod.GET)
	@ResponseBody
	public Msg getSubscribeIdWithDevice(@RequestParam("subscribe_id") String subscribe_id) {
		List<Subscribe> list = subscribeService.getByPrimaryKeyWithDevice(subscribe_id);
		if(list.size()>0){
			List<SubscribeSon> list2 = subscribeSonService.selectBySubscribeId(subscribe_id);
			return Msg.success().add("getSubscribeDetailedWithDeviceDataBySubscribeId", list).add("subscribeSon", list2);
		}else{
			return Msg.fail();
		}
	}
	//管理端推送
	public List<Subscribe> WithDeviceBySubscribeId(String subscribe_id) {
		List<Subscribe> list = subscribeService.getByPrimaryKeyWithDevice(subscribe_id);
		return list;
//		if(list.size()>0){
//			List<SubscribeSon> list2 = subscribeSonService.selectBySubscribeId(subscribe_id);
//			return Msg.success().add("getSubscribeDetailedWithDeviceDataBySubscribeId", list).add("subscribeSon", list2);
//		}else{
//			return Msg.fail();
//		}
	}

	//根据设备ID和开始时间和结束时间查询
	@RequestMapping(value = "/getSubscribeByIdAndTime", method = RequestMethod.GET)
	@ResponseBody
	public synchronized Msg getIdAndTime(@RequestParam("subscribe_device_id") String subscribe_device_id,
			@RequestParam("subscribe_begintime") String subscribe_begintime,
			@RequestParam("subscribe_endtime") String subscribe_endtime) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
//		if(df.parse(subscribe_begintime) == df.parse(df.format(new Date()))){
//			
//		}
		List list = subscribeService.getIdAndTime(subscribe_device_id, df.parse(subscribe_begintime),
				df.parse(subscribe_endtime));
		try {
			Thread.sleep(100);
		} catch (Exception e) {
		}
		if (list.size() != 0) {
			return Msg.fail().add("getSubscribeByIdAndTime", list);
		} else {
			return Msg.success().add("successMsg", "时间合理");
		}
	}
	
	
	//根据开始时间和结束时间查询
	@RequestMapping(value = "/getSubscribeByStartTimeAndEndTime", method = RequestMethod.GET)
	@ResponseBody
	public  Msg getSubscribeByStartTimeAndEndTime(
			@RequestParam("subscribe_begintime") String subscribe_begintime,
			@RequestParam("subscribe_endtime") String subscribe_endtime) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		List list = subscribeService.getIdAndTime1(df.parse(subscribe_begintime),df.parse(subscribe_endtime));
		if(list.size()>0){
			return Msg.success().add("success", list);
		}else{
			return Msg.fail();
		}	
		
	}

	//插入一条预约记录
	@RequestMapping(value = "/insertSubscribe")
	@ResponseBody
	public Msg insert(
			@RequestParam("subscribe_user_email") String subscribe_user_email,
			@RequestParam("subscribe_device_id") String subscribe_device_id,
			@RequestParam("subscribe_begin_time") String subscribe_begin_time,
			@RequestParam("subscribe_end_time") String subscribe_end_time,
			@RequestParam("subscribe_user_mobile") String subscribe_user_mobile,
			@RequestParam("subscribe_remark") String subscribe_remark) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		String uuid = UUID.randomUUID().toString().substring(0, 31);// 32位UUID
		Subscribe sub = new Subscribe();
		Person person = new Person();
		// 根据工号和姓名查员工是否存在
		person.setEmail(subscribe_user_email);
		List<Person> list = personService.selectByPersonEmail(person);
		if (list.size() != 0) {
			sub.setSubscribeUserId(list.get(0).getEmail());
			int i = getIdAndTime(subscribe_device_id, subscribe_begin_time, subscribe_end_time).getCode();// 判断时间是否合理
			if ((df.parse(df.format(new Date()))).getTime() < (df.parse(subscribe_begin_time)).getTime()
					&& (df.parse(df.format(new Date()))).getTime() < (df.parse(subscribe_end_time)).getTime()
					&& i == 1) {
				sub.setSubscribeUserId(list.get(0).getUserid());//
				sub.setSubscribeUserEmail(subscribe_user_email);
				sub.setSubscribeDeviceId(subscribe_device_id);
				sub.setSubscribeBeginTime(df.parse(subscribe_begin_time));
				sub.setSubscribeEndTime(df.parse(subscribe_end_time));
				sub.setSubscribeUserName(list.get(0).getUsertruename());
				sub.setSubscribeOrganizeName(list.get(0).getOrganizeallname());
				sub.setSubscribeUserMobile(subscribe_user_mobile);
				sub.setSubscribeRemark(subscribe_remark);
				sub.setId(uuid);
				sub.setSubscribeCreatetime(df.parse(df.format(new Date())));
				sub.setSubscribeStatus("2");// 默认 2通过 1.未通过2通过3正常结束4撤销5停止
				sub.setFlag(1);// 默认为1没删除 0、删除1、没删除
				int a = subscribeService.insertSelective(sub);
				if (a == 1) {
					return Msg.success().add("successMsg", "预约成功");
				} else {
					return Msg.fail().add("failMsg", "预约失败");
				}
			} else
				return Msg.fail().add("failMsg", "时间冲突");
		} else {
			return Msg.fail().add("failMsg", "该用户不存在");
		}

	}

	//插入一条预约记录app
	@RequestMapping(value = "/insertSubscribeForApp",method = RequestMethod.GET)
	@ResponseBody
	public Msg insertForApp(@RequestParam("subscribe_user_id") String subscribe_user_id,
			@RequestParam("subscribe_user_email") String subscribe_user_email,
			@RequestParam("subscribe_device_id") String subscribe_device_id,
			@RequestParam("subscribe_begin_time") String subscribe_begin_time,
			@RequestParam("subscribe_end_time") String subscribe_end_time,
			@RequestParam("subscribe_user_name") String subscribe_user_name,
			@RequestParam("subscribe_user_mobile") String subscribe_user_mobile,
			@RequestParam("subscribe_remark") String subscribe_remark,
			@RequestParam("subscribe_organize_id") String subscribe_organize_id,
			@RequestParam("subscribe_sons") String jsonStr
			) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		String uuid = UUID.randomUUID().toString().substring(0, 31);// 32位UUID
		Subscribe sub = new Subscribe();
		Organize org = new Organize();
	    org.setId(subscribe_organize_id);
	    List<Organize> orgList = organizeService.selectByOrganizeId(org);
		sub.setSubscribeUserId(subscribe_user_id);
		if ((df.parse(df.format(new Date()))).getTime() < (df.parse(subscribe_begin_time)).getTime()
				&& (df.parse(df.format(new Date()))).getTime() < (df.parse(subscribe_end_time)).getTime()) {
			sub.setSubscribeUserEmail(subscribe_user_email);
			sub.setSubscribeDeviceId(subscribe_device_id);
			sub.setSubscribeBeginTime(df.parse(subscribe_begin_time));
			sub.setSubscribeEndTime(df.parse(subscribe_end_time));
			sub.setSubscribeUserName(subscribe_user_name);
			sub.setSubscribeUserMobile(subscribe_user_mobile);
			sub.setSubscribeRemark(subscribe_remark);
			sub.setSubscribeOrganizeName(orgList.get(0).getName());//部门名称
			sub.setId(uuid);
			sub.setSubscribeCreatetime(df.parse(df.format(new Date())));
			sub.setSubscribeStatus("2");// 默认 2通过 1.未通过2通过3正常结束4撤销5停止
			sub.setFlag(1);// 默认为1没删除 0、删除1、没删除
			String times = this.timeToTime(sub.getSubscribeBeginTime(), sub.getSubscribeEndTime());//2018-5-16时间拼接、消息推送
			// 判断时间是否合理
			System.out.println("预约子表数据 = "+jsonStr);
			if (getIdAndTime(subscribe_device_id, subscribe_begin_time, subscribe_end_time).getCode() == 1) {
				if (subscribeService.insertSelective(sub) == 1) {
					//String jsonStr = "[{'email':'byw_cgb@faw.com.cn','mobile':'13804310597','userid': '8a05c12f4b4959c0014b495a3e4d02ff','username': '白宇威'},{'email':'fff_ffb@faw.com.cn','mobile':'1388888888','userid': '8a05c12f4b4959c0014b495a3e4d02ff','username': '电放费'}]";
					// 受邀人--批量添加
					if(jsonStr != "" || !jsonStr.equals("")){
						JSONArray jsona = JSONArray.fromObject(jsonStr); // 传入字符串
						SubscribeSon subson = new SubscribeSon();
						String uuidson="";
						for (int i = 0; i < jsona.size(); i++) {
							JSONObject jsono = jsona.getJSONObject(i);
							uuidson = UUID.randomUUID().toString().substring(0, 31);// 32位UUID
							Organize orgSon = new Organize();
							orgSon.setId(jsono.getString("userteamid"));
							List<Organize> orgSonList = organizeService.selectByOrganizeId(orgSon);
						    org.setId(subscribe_organize_id);
							subson.setId(uuidson);
							subson.setSubscribeId(uuid);
							subson.setSubscribePartner(jsono.getString("userid"));
							subson.setSubscribeUserName(jsono.getString("username"));
							subson.setSubscribePartnerId(jsono.getString("email"));// email
							subson.setSubscribeUserMobile(jsono.getString("mobile"));
							subson.setSubSonOrgName(orgSonList.get(0).getName());//部门名称
							//subson.setSubscribeRemark(jsona.getString("remark"));
							subscribeSonController.insertSubscribeSon(subson);
						}
						//消息推送2018-5-15
						String son="";
						String sonEmail="";
						for (int i = 0; i < jsona.size(); i++) {
							JSONObject jsono = jsona.getJSONObject(i);
							if(i==jsona.size()-1){
								son=son+jsono.getString("username");
							}else{
								son=son+jsono.getString("username")+",";
							}
						}
						Device device = deviceService.getDevice(subscribe_device_id);//获取设备信息
						String content="您预约了"+device.getDeviceType()+device.getDeviceNumber()+",时间:"+times+",位置:"+device.getDevicePlace()+",邀约的伙伴:"+son+"。备注:"+subscribe_remark;
						String title = "健身预约通知";
						String urlsss = baseParameter.getPushUrlBegin()+uuid+baseParameter.getPushUrlEnd();// 业务系统跳转地址
						System.out.println("email:"+subscribe_user_email+"\n"+"信息内容:"+content+"\n"+"标题:"+title+"\n"+"业务系统跳转地址:"+urlsss);
						this.pushMessage(subscribe_user_email, content, title, urlsss);
						for (int i = 0; i < jsona.size(); i++) {
							JSONObject jsonopush = jsona.getJSONObject(i);
							if(i==jsona.size()-1){
								sonEmail=sonEmail+jsonopush.getString("email");
							}else{
							sonEmail=sonEmail+jsonopush.getString("email")+"|";
							}
						}
						Person per = new Person();
						per.setEmail(subscribe_user_email);
						List<Person> listp = personService.selectByPersonEmail(per);//获取姓名
						String contentson=listp.get(0).getUsertruename()+"邀请您在"+times+",做"+device.getDeviceType()+device.getDeviceNumber()+"运动,位置:"+device.getDevicePlace()+",备注:"+subscribe_remark;
						String titleson = "健身受邀通知";
						//String urlssson="http://fawyy.sunnyit.cn:8222/Subscribe/app/html/MyInviteDetailed.html?state=0&flagePage=MyInvite";// 业务系统跳转地址
						//String urlssson = baseParameter.getPushUrlSon0();
						String urlssson = baseParameter.getPushUrlSonBegin()+uuidson+baseParameter.getPushUrlSonEnd();
						System.out.println("email:"+sonEmail+"\n"+"信息内容:"+contentson+"\n"+"标题:"+titleson+"\n"+"业务系统跳转地址:"+urlssson);
						this.pushMessage(sonEmail, contentson, titleson, urlssson);
						//向管理端推送最新预约信息
						WebSocketTest webso = new WebSocketTest();
						List<Subscribe> list = this.WithDeviceBySubscribeId(uuid);
						String ti = this.timeToTime(list.get(0).getSubscribeBeginTime(), list.get(0).getSubscribeEndTime());
						webso.onMessage(list.get(0).getSubscribeUserName()+"预约了"+ti+"的"+list.get(0).getDeviceType()+list.get(0).getDeviceNumber(), null);
						return Msg.success().add("successMsg", "您与小伙伴们预约成功").add(" message", uuid);
					}else{
						//消息推送2018-5-15
						Device device = deviceService.getDevice(subscribe_device_id);
						String content="您预约了"+device.getDeviceType()+device.getDeviceNumber()+",时间:"+times+",位置:"+device.getDevicePlace()+",备注:"+subscribe_remark;
						String title = "健身预约通知";
						//String urlsss="http://fawyy.sunnyit.cn:8222/Subscribe/app/html/OrderDetailed.html?OrderId="+uuid+"&Pageflage=MyOrderPage";// 业务系统跳转地址
						String urlsss = baseParameter.getPushUrlBegin()+uuid+baseParameter.getPushUrlEnd();// 业务系统跳转地址
						System.out.println("email:"+subscribe_user_email+"\n"+"信息内容:"+content+"\n"+"标题:"+title+"\n"+"业务系统跳转地址:"+urlsss);
						this.pushMessage(subscribe_user_email, content, title, urlsss);
						//向管理端推送最新预约信息
						WebSocketTest webso = new WebSocketTest();
						List<Subscribe> list = this.WithDeviceBySubscribeId(uuid);
						String ti = this.timeToTime(list.get(0).getSubscribeBeginTime(), list.get(0).getSubscribeEndTime());
						webso.onMessage(list.get(0).getSubscribeUserName()+"预约了"+ti+"的"+list.get(0).getDeviceType()+list.get(0).getDeviceNumber(), null);
						return Msg.success().add("successMsg", "预约成功").add("message", uuid);
					}
				} else
					return Msg.fail().add("failMsg", "预约信息添加失败");
			} else
				return Msg.fail().add("failMsg", "时间冲突");
		} else
			return Msg.fail().add("failMsg", "时间有误");

	}

	//根据预约id修改状态***1未通过2通过3正常结束4撤销5终止
	@RequestMapping(value = "/updateSubscribeStatusById")
	@ResponseBody
	public Msg updateStatus(@RequestParam("subscribe_id") String subscribe_id,
			@RequestParam("subscribe_status") String subscribe_status,
			@RequestParam("subscribe_result") String subscribe_result) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		Subscribe record = new Subscribe();
		record.setId(subscribe_id);
		record.setSubscribeBackouttime(df.parse(df.format(new Date())));
		record.setSubscribeStatus(subscribe_status);
		record.setSubscribeResult(subscribe_result);
		//子表撤销
			SubscribeSon subson = new SubscribeSon();
			subson.setSubscribeId(subscribe_id);
			subson.setSubscribeStatus(subscribe_status);
			subson.setSubscribeResult(subscribe_result);
			if(subscribe_status.equals("4")){
				subson.setSubscribeUserStatus("3");
				//消息推送
				List<Subscribe> listsub = subscribeService.getByPrimaryKeyWithDevice(subscribe_id);//获取预约信息、带设备信息--推送
				String times = this.timeToTime(listsub.get(0).getSubscribeBeginTime(), listsub.get(0).getSubscribeEndTime());//2018-5-16时间拼接、消息推送
				List<SubscribeSon> listsubson = subscribeSonService.selectBySubscribeIdForPushMessage(subscribe_id);//获取受邀信息--推送
				String sonEmail="";
				if(listsubson.size()>0){
					subscribeSonService.updateByPrimaryKeySelective(subson);
					Person person = new Person();
					person.setUserid(listsub.get(0).getSubscribeUserId());
					List<Person> listperson = personService.selectByPersonUserId(person);
					//子表撤销消息推送
					for(int i= 0;i<listsubson.size();i++){
						if(i==listsubson.size()-1){
							sonEmail=sonEmail+listsubson.get(i).getSubscribePartnerId();
						}else{
						sonEmail=sonEmail+listsubson.get(i).getSubscribePartnerId()+"|";
						}
					}
					String contentson=listperson.get(0).getUsertruename()+"撤销了在"+times+"的"+listsub.get(0).getDeviceType()+listsub.get(0).getDeviceNumber()+"运动,位置:"+listsub.get(0).getDevicePlace()+",原因:"+subscribe_result;
					String titleson="健身撤销通知";
					//String urlssson = baseParameter.getPushUrlSon3();
					String urlssson = baseParameter.getPushUrlSonBegin()+listsubson.get(0).getId()+baseParameter.getPushUrlSonEnd();
					System.out.println("email:"+sonEmail+"\n"+"信息内容:"+contentson+"\n"+"标题:"+titleson+"\n"+"业务系统跳转地址:"+urlssson);
					this.pushMessage(sonEmail, contentson, titleson, urlssson);
				}
				String content="您撤销了在"+times+"的"+listsub.get(0).getDeviceType()+listsub.get(0).getDeviceNumber()+"运动,位置:"+listsub.get(0).getDevicePlace()+",原因:"+subscribe_result;
				String title="健身撤销通知";
				String urlss = baseParameter.getPushUrlBegin()+listsub.get(0).getId()+baseParameter.getPushUrlEnd();// 业务系统跳转地址
				System.out.println("email:"+listsub.get(0).getSubscribeUserEmail()+"\n"+"信息内容:"+content+"\n"+"标题:"+title+"\n"+"业务系统跳转地址:"+urlss);
				this.pushMessage(listsub.get(0).getSubscribeUserEmail(), content, title, urlss);
			}else if(subscribe_status.equals("5")){
				subscribeSonService.updateByPrimaryKeySelective(subson);
			}
		if (subscribeService.updateStatusAndFlag(record) == 1) {
			return Msg.success().add("successMsg", "修改状态成功");
		} else
			return Msg.fail().add("failMsg", "修改状态失败");
	}
//	@RequestMapping(value = "/updateSubscribeStatusById")
//	@ResponseBody
//	public Msg updateStatus(@RequestParam("subscribe_id") String subscribe_id,
//			@RequestParam("subscribe_status") String subscribe_status,
//			@RequestParam("subscribe_result") String subscribe_result) throws Exception {
//		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
//		Subscribe record = new Subscribe();
//		record.setId(subscribe_id);
//		record.setSubscribeBackouttime(df.parse(df.format(new Date())));
//		record.setSubscribeStatus(subscribe_status);
//		record.setSubscribeResult(subscribe_result);
//		//子表撤销
//			SubscribeSon subson = new SubscribeSon();
//			subson.setSubscribeId(subscribe_id);
//			subson.setSubscribeStatus(subscribe_status);
//			subson.setSubscribeResult(subscribe_result);
//			if(subscribe_status.equals("4")){
//				subson.setSubscribeUserStatus("3");
//			}
//			subscribeSonService.updateByPrimaryKeySelective(subson);
//		if (subscribeService.updateStatusAndFlag(record) == 1) {
//			return Msg.success().add("successMsg", "修改状态成功");
//		} else
//			return Msg.fail().add("failMsg", "修改状态失败");
//	}
	
	//根据设备id修改状态***4撤销--2018-5-2后台管理用
	@RequestMapping(value = "/updateSubscribeStatusByDeviceId")
	@ResponseBody
	public Msg updateSubscribeStatusByDeviceId(String device_id,String subscribe_result,String subscribe_status,String subscribe_user_status) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		Subscribe record = new Subscribe();
		record.setSubscribeDeviceId(device_id);//设备id
		record.setSubscribeBackouttime(df.parse(df.format(new Date())));
		record.setSubscribeStatus(subscribe_status);
		record.setSubscribeResult(subscribe_result);
		//多条子表撤销
		List<Subscribe> list = subscribeService.selectSubscribeIdByDeviceId(device_id);
		if(list.size()>0)
			for(int i=0;i<list.size();i++){
				SubscribeSon subson = new SubscribeSon();
				subson.setSubscribeId(list.get(i).getId());
				subson.setSubscribeStatus(subscribe_status);
				subson.setSubscribeResult(subscribe_result);
				//if(subscribe_status.equals("4")){
					subson.setSubscribeUserStatus(subscribe_user_status);
				//}
				subscribeSonService.updateByPrimaryKeySelective(subson);
			}
		if (subscribeService.updateByDeviceId(record) == 1) {
			return Msg.success().add("successMsg", "修改状态成功");
		} else
			return Msg.fail().add("failMsg", "修改状态失败");
	}
	
	//根据设备id修改状态***修改为原来状态--2018-5-2后台管理用
	@RequestMapping(value = "/updateSubscribeStatusByDeviceIdTwo")
	@ResponseBody
	public Msg updateSubscribeStatusByDeviceIdTwo(String device_id,String subscribe_result,String subscribe_status,String subscribe_user_status) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		Subscribe record = new Subscribe();
		record.setSubscribeDeviceId(device_id);//设备id
		record.setSubscribeBackouttime(df.parse(df.format(new Date())));
		record.setSubscribeStatus(subscribe_status);
		record.setSubscribeResult(subscribe_result);
		record.setSubscribeRemark("管理员:设备已损坏,维修中...");//管理员:设备已损坏,维修中...
		record.setSubscribeOrganizeName("管理员:设备已下线...");//管理员:设备已下线...
		//多条子表撤销
		List<Subscribe> list = subscribeService.selectSubscribeIdByDeviceIdTwo(device_id);
		System.out.println(list.toString());
		if(list.size()>0)
			for(int i=0;i<list.size();i++){
				SubscribeSon subson = new SubscribeSon();
				subson.setSubscribeId(list.get(i).getId());
				subson.setSubscribeStatus(subscribe_status);
				subson.setSubscribeResult(subscribe_result);
				//if(subscribe_status.equals("4")){
					subson.setSubscribeUserStatus(subscribe_user_status);
				//}
				subscribeSonService.updateByPrimaryKeySelective(subson);
			}
		if (subscribeService.updateByDeviceIdTwo(record) == 1) {
			return Msg.success().add("successMsg", "修改状态成功");
		} else{
			return Msg.fail().add("failMsg", "修改状态失败");
			}
	}

	//根据预约id修改状态值***0删除1没删除 管理员用
	@RequestMapping(value = "/updateSubscribeFlagById")
	@ResponseBody
	public Msg updateFlag(@RequestParam("subscribe_id") String subscribe_id,
			@RequestParam("subscribe_result") String subscribe_result) throws Exception {
//		Subscribe record = new Subscribe();
//		record.setId(subscribe_id);
//		record.setSubscribeResult(subscribe_result);
//		record.setFlag(0);
		String[] id = subscribe_id.split(",");
//		if (subscribeService.updateStatusAndFlag(record) == 1) {
		if (subscribeService.updateFlag(id) >= 1) {
			return Msg.success().add("successMsg", "删除成功");
		} else
			return Msg.fail().add("failMsg", "删除失败");
	}
	
	//web、service通过预约人email查询今天预约简略信息-推送
	@RequestMapping(value = "/selectMessageByEmailWebService", method = RequestMethod.GET)
	@ResponseBody
	public Msg selectMessageByEmailWebService(String email) throws Exception {
		Subscribe record = new Subscribe();
		record.setSubscribeUserEmail(email);
		List<Subscribe> list = subscribeService.selectMessageByEmailWebService(record);
		if (list.size()>0) {
			return Msg.success().add("success", list);
		} else
			return Msg.fail().add("fail", "数据为空");
	}
	//web、service查询今天预约简略信息-推送2018-5-15
	@RequestMapping(value = "/selectToDayMessageWebService", method = RequestMethod.GET)
	@ResponseBody
	public String selectToDayMessageWebService() throws Exception {
		List<Subscribe> list = subscribeService.selectToDayMessageWebService();
		String message = subscribeService.ProLogList2Json(list).toString();
		return "{\"message\":"+message+",\"number\":"+list.size()+"}";
	}
	
	//消息推送封装2018-5-15
	public void pushMessage(String touser,String content,String title,String urlsss){
		try {
			String surl = "http://10.7.65.5:9080/fawportal/app/push_message.jsp?";
			//String surl = "http://mobile.faw.com.cn:8089/fawportal/app/push_message.jsp?";// "http://10.133.73.49:8080/workflow/push_message.jsp?";
			surl += "&appid=" + URLEncoder.encode("FAW_JSXT", "UTF-8");
			URL url = new URL(surl);
			URLConnection con = url.openConnection();
			System.out.println("Received a : " + con.getClass().getName());
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			con.setRequestProperty("Content-type", "text/html");
			con.setRequestProperty("Accept-Charset", "UTF-8");
			con.setRequestProperty("contentType", "UTF-8");
			String msg = "Hi HTTP SERVER! Just a quick hello!";
			con.setRequestProperty("CONTENT_LENGTH", "" + msg.length()); // Not
			System.out.println("Getting an output stream...");
			//DataOutputStream osw = new DataOutputStream(con.getOutputStream());
			OutputStreamWriter osw =new OutputStreamWriter(con.getOutputStream(), "UTF-8");
			JSONObject json = new JSONObject();
			json.put("touser", touser);// 邮箱
			json.put("msgtype", "text");
			json.put("content", content);// 根据业务内容st拼接，在手机消息通知显示
			json.put("title", title);
			//String urlss = "http://mobile.faw.com.cn:8089/jszx/app/html/EquipmentDisplay.html";//跳转地址
			json.put("msgurl", urlsss);// 业务系统跳转地址
			osw.write(json.toString());
			osw.flush();
			osw.close();
			InputStream is = con.getInputStream();
			InputStreamReader isr = new InputStreamReader(is,"UTF-8");
			BufferedReader br = new BufferedReader(isr);
			String line = null;
			while ((line = br.readLine()) != null) {
				System.out.println("line: " + line);
			}
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}
	//修改时间格式2018-5-16
	public String timeToTime(Date time1,Date time2){
		SimpleDateFormat bartDateFormat = new SimpleDateFormat("MM-dd-EEEE HH:mm");
		SimpleDateFormat bartDateFormat2 = new SimpleDateFormat("HH:mm");
		System.out.println(bartDateFormat.format(time1)+"~"+bartDateFormat2.format(time2));
		String timeStr = (bartDateFormat.format(time1)+"~"+bartDateFormat2.format(time2)).toString();
		return timeStr;
	}

		
	
}
